import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';
import Layout from '@/layout/index.vue';

// 添加公共路由
const constantFiles = require.context('./constantModules', true, /\.ts$/);
let constantModules: Array<RouteRecordRaw> = [];
constantFiles.keys().forEach((key) => {
  if (key === './index.ts') return;
  constantModules = constantModules.concat(constantFiles(key).default);
});

// 添加异步路由
const asyncFiles = require.context('./permissionModules', true, /\.ts$/);
let permissionModules: Array<RouteRecordRaw> = [];
asyncFiles.keys().forEach((key) => {
  if (key === './index.ts') return;
  permissionModules = permissionModules.concat(asyncFiles(key).default);
});

export const constantRoutes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Home',
    component: Layout,
    meta: { title: '首页', hidden: true },
    redirect: '/system/monitor',
  },
  ...constantModules,
];

export const asyncRoutes: Array<RouteRecordRaw> = [
  ...permissionModules.sort((a, b) => (a.meta as any).index - (b.meta as any).index),
];

const router = createRouter({
  history: createWebHashHistory(),
  routes: constantRoutes,
});

// 重置路由
export function resetRouter(): void {
  const newRouter = router;
  (router as any).matcher = (newRouter as any).matcher;
}

export default router;
